import React, { useContext } from "react";
import styles from "../css/order.module.css";
import { Button, Form, Input } from "antd-mobile";
import { useDispatch, useSelector } from "react-redux";
import { addPsg, removePsg } from "../../../store/slice/orderSlice";
import { FormContent } from "../Fform";
import { useNavigate } from "react-router-dom";
function ChoosePer() {
  let dis = useDispatch();
  let form = useContext(FormContent);
  const psgArr = useSelector((store) => store.order.psgArr);
  console.log(psgArr);
  const onFinish = (values) => {
    console.log(values);
  };
  // const [form] = Form.useForm();
  //点击添加成人
  const add = () => {
    const list = { ticketType: "成人票" };
    dis(addPsg(list));
    form.setFieldValue("contacts", [...psgArr, list]);
  };
  let nav = useNavigate();
  return (
    <div className={styles.personbox}>
      <Form
        form={form}
        onFinish={onFinish}
        initialValues={{
          contacts: psgArr,
        }}
        mode="card"
        layout="horizontal"
        style={{ "--prefix-width": "80px" }}
      >
        <Form.Array
          name="contacts"
          onAdd={(operation) => operation.add({ name: "" })}
          renderHeader={({ index }, { remove }) => (
            <div>
              <span>
                乘车人{index + 1}-{psgArr[index]?.ticketType}
              </span>
              <a
                onClick={() => {
                  //界面移出
                  remove(index);
                  //仓库移出
                  dis(removePsg(index));
                }}
                style={{ float: "right" }}
              >
                删除
              </a>
            </div>
          )}
        >
          {(fields) =>
            fields.map(({ index }) => (
              <>
                <Form.Item
                  name={[index, "name"]}
                  label="姓名"
                  rules={[{ required: true, message: "姓名不能为空" }]}
                >
                  <Input placeholder="乘客姓名" />
                </Form.Item>
                <Form.Item
                  name={[index, "idcard"]}
                  label="身份证"
                  rules={[
                    { required: true, message: "证件号码不能为空" },
                    {
                      pattern: /^\d{17}(\d|X|x)$/,
                      message: "身份证格式不正确",
                    },
                  ]}
                >
                  <Input placeholder="证件号码" />
                </Form.Item>
              </>
            ))
          }
        </Form.Array>
      </Form>
      <div className={styles.btn}>
        <Button color="primary" size="mini" fill="none" onClick={add}>
          添加成人
        </Button>
        <Button
          color="primary"
          size="mini"
          fill="none"
          onClick={() => nav("/psg?mode=choose")}
        >
          选择乘客
        </Button>
      </div>
    </div>
  );
}

export default ChoosePer;
